package com.heima.common.identity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.heima.utils.common.HttpUtils;
import okhttp3.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 身份认证工具类
 */
public class IdentityAuthenticationUtil {

    /**
     * 身份认证工具
     *
     * @param name 姓名
     * @param idNo 身份证号码
     * @return json字符串
     * @throws IOException
     */
    public static String postData(String name, String idNo) throws IOException {
        String url = "https://idenauthen.market.alicloudapi.com/idenAuthentication";
        String appCode = "0c5fdfe48c3642c98369e1bcab57ba1b";
        String result = "";
        RequestBody formBody = new FormBody.Builder().add("name", name).add("idNo", idNo).build();
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).post(formBody).build();

        Call call = new OkHttpClient().newCall(request);
        Response response = null;
        try {
            response = call.execute();
        } catch (IOException e) {
            System.out.println("execute failed, message:" + e.getMessage());
        }

        assert response != null;
        if (!response.isSuccessful()) {      // 当返回结果发生错误时
            // 状态码为403时一般是套餐包用尽，需续购；注意：续购不会改变秘钥（appCode），仅增加次数
            // 续购链接：https://market.aliyun.com/products/57000002/cmapi025518.html
            System.out.println("request failed----" + "返回状态码" + response.code() + ",message:" + response.message());
        }
        result = response.body().string();    //此处不可以使用toString()方法，该方法已过期

        return result;
    }

    /**
     * 获取图片中的身份信息
     * @param side 身份证正/反面
     * @param image 身份证图片
     * @return 身份证信息
     * @throws IOException
     */
    public static String postData2(String side, byte[] image) throws IOException {
        String host = "https://cardnumber.market.alicloudapi.com";
        String path = "/rest/160601/ocr/ocr_idcard.json";
        String appcode = "0c5fdfe48c3642c98369e1bcab57ba1b";
        //String imgFile = "http://192.168.88.2:9000/heima-leadnews/2025/04/10/9e5097036df043be960d0dc6ff758bac.jpg";
        String method = "POST";

        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");

        Map<String, String> querys = new HashMap<String, String>();
        InputStream inputStream = new ByteArrayInputStream(image);
//        finputstream.read(image);
//        finputstream.close();
        String imgBase64 = new String(Base64.encodeBase64(image));
        //configure配置
        JSONObject configObj = new JSONObject();
        configObj.put("side", side);
        String config_str = configObj.toString();

        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        requestObj.put("image", imgBase64);
        if (configObj.size() > 0) {
            requestObj.put("configure", config_str);
        }
        String bodys = requestObj.toString();

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            int stat = response.getStatusLine().getStatusCode();
            if (stat != 200) {
                System.out.println("Http code: " + stat);
                System.out.println("http header error msg: " + response.getFirstHeader("X-Ca-Error-Message"));
                System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity()));
                return null;
            }

            String res = EntityUtils.toString(response.getEntity());
            JSONObject res_obj = JSON.parseObject(res);

            //System.out.println(res_obj.toJSONString());
            return res_obj.toJSONString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}